<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    @ok="handleOK"
    @cancel="closeModalAndReset"
   :title="t('sys.script.details')"
  >
    <Description :column="3" :data="mockData" :schema="schema" />
    <div class="tabelview">
      <BasicTable @register="registerTableModel">
        <template #resetBefore>
          <Button @click="toggleSelectAll" style="margin-right: 10px">
            <template #icon>
              <!-- <CheckOutlined v-if="isAllSelected" /> -->
              <!-- <CloseOutlined v-else /> -->
            </template>
            {{ buttonTitle }}
          </Button>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { Description, DescItem } from '@/components/Description';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { ref, computed, h, onBeforeUnmount } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { getDetailAPI, getMatchMaxAPI, matchListAPI } from '@/api/demo/InformationMatching';
  import { columnsModels } from './account.data';
  import { Progress, Tooltip, Button, Input } from 'ant-design-vue';
  import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import { detailPageAPI } from '@/api/demo/AdvertisingMarketing';
  import { VNode } from 'vue'; // 确保 VNode 类型正确
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const matching = ref('0.2');
  const selectedCount = ref(0); // 初始化选中的数量
  const emit = defineEmits(['success']);
  const Data = ref<any>({});
  const dataSource = ref<any[]>([]);
  const buttonTitle = ref('全选所有筛选结果');
  const buttonLabels = ref<{ label: string; value: number }[]>([]);
  const mockData = ref({});
  const isAllSelected = ref(false);
  const selectedLabels = ref<string[]>([]);
  defineOptions({ name: 'AccountModal' });

  const schema: DescItem[] = [
    { field: 'id', label: 'id', labelMinWidth: 150 },
    { field: 'createTime', label: t('sys.informaionMatchaing.columns.createTime'), labelMinWidth: 150 },
    { field: 'title', label: t('sys.informaionMatchaing.columns.title'), labelMinWidth: 150 },
    { field: 'content', label: t('sys.configuration.describe'), labelMinWidth: 150 },
    { field: 'district', label:  t('sys.informaionMatchaing.columns.district'), labelMinWidth: 150 },
    { field: 'audience', label:  t('sys.informaionMatchaing.columns.audience'), labelMinWidth: 150 },
    { field: 'interest', label:  t('sys.informaionMatchaing.columns.interest'), labelMinWidth: 150 },
    {
      field: 'status',
      label: t('sys.informaionMatchaing.columns.status'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        if (data.status === 0) return t('sys.configuration.notStart');
        if (data.status === 1) return '执行中';
        return '执行成功';
      },
    },
    {
      field: 'success',
      label: t('sys.informaionMatchaing.columns.success'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        const success = data.success ?? '-';
        const total = data.total ?? '-';
        return `${success}/${total}`;
      },
    },
  ];

  const searchFormSchemaDtail: FormSchema[] = [
    {
      field: 'matching',
      label: t('sys.informaionMatchaing.columns.matching'),
      component: 'Input',
      colProps: { span: 4 },
      defaultValue: '0.2',
      render: ({ model, field }) => {
        return h(Input, {
          value: model[field],
          onInput: (event) => {
            model[field] = event.target.value;
          },
          onBlur: (event) => {
            matching.value = event.target.value;
            reload();
            selectedCount.value = 0;
            clearSelectedRowKeys(); // 清空复选框的所有勾选
          },
          style: {
            border: '1px solid #d9d9d9', // 添加边框样式
            borderRadius: '4px', // 添加圆角样式
            padding: '4px 11px', // 添加内边距
          },
        });
      },
    },
  ];

  const isUpdate = ref(true);
  const modalWidth = ref('60%');

  interface FormSchema {
    field: string;
    label: string;
    component: string;
    colProps: { span: number };
    defaultValue?: string;
    render?: ({ model, field }: { model: any; field: string }) => VNode;
  }

  const modalTitle = computed(() => {
    if (!selectedCount.value) {
      return '请勾选视频';
    } else {
      return `您选择了匹配度大于 ${matching.value} 的视频 共 ${selectedCount.value} 条`;
    }
  });

  const [registerTableModel, { reload, setSelectedRowKeys, getSelectRows, clearSelectedRowKeys }] =
    useTable({
      title: modalTitle,
      api: async ({ page, pageSize }) => {
        const result = await detailPageAPI({
          ...Data.value,
          page,
          pageSize,
        });
        return result;
      },
      rowKey: 'dataId',
      columns: columnsModels,
      showTableSetting: true,
      bordered: true,
      handleSearchInfoFn(info) {
        return info;
      },
      formConfig: {
        schemas: searchFormSchemaDtail,
        autoSubmitOnEnter: true,
        labelAlign: 'left',
        onFormValuesChange: (changedValues, allValues) => {
          // 获取 matching 值
          matching.value = allValues.matching;
        },
      },
      useSearchForm: true,
      rowSelection: {
        type: 'checkbox',
        onChange: (selectedRowKeys, selectedRows) => {
          selectedCount.value = selectedRows.length;
        },
      },
    });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    Data.value = data.record;
    mockData.value = data.record;
    dataSource.value = [Data.value];
    getMatchMax();
    setModalProps({ confirmLoading: false, showOkBtn: true });
    await reload();
  });

  async function handleOK() {
    const selectedRows = getSelectRows();
    const urls = selectedRows.map((row) => row.userNo).filter((userNo) => userNo);
    const combinedUrls = [...urls, ...selectedLabels.value];
    emit('success', { urls: combinedUrls });
    closeModal();
  }

  async function getMatchMax() {
    let valueData = await getMatchMaxAPI(Data.value.id);
    // 只处理前5个数据项
    buttonLabels.value = valueData.data.slice(0, 5).map((item) => ({
      label: Number(item.label).toFixed(2),
      value: item.value,
    }));
  }

  const handleButtonClick = (model, field, label) => {
    model.matching = label.label;
    matching.value = label.label;
  };

  const toggleSelectAll = async () => {
    isAllSelected.value = !isAllSelected.value;

    if (isAllSelected.value) {
      buttonTitle.value = '取消选择所有筛选';
      let value = await matchListAPI({
        ...Data.value,
        matching: searchFormSchemaDtail.value[0].defaultValue,
      });
      selectedLabels.value = value.data.map((item: { label: string }) => item.label);
      // 更新表格的选中状态
      let setSelectedRowKeysNum: number[] = [];

      value.data.forEach((item) => {
        setSelectedRowKeysNum.push(Number(item.value));
      });
      setSelectedRowKeys(setSelectedRowKeysNum);
    } else {
      buttonTitle.value = '全选所有筛选结果';
      selectedLabels.value = [];
      clearSelectedRowKeys();
    }
  };

  onBeforeUnmount(() => {
    isAllSelected.value = false;
  });

  function closeModalAndReset() {
    selectedCount.value = 0;
    isAllSelected.value = false;
    buttonTitle.value = '全选所有筛选结果';
  }
</script>

<style scoped>
  .tabelview :deep(.vben-basic-table-form-container .ant-form) {
    margin: 0 !important;
    padding-bottom: 0 !important;
  }
</style>
